package com.lms.admin.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lms.admin.base.mapper.SysRoleMapper;
import com.lms.admin.base.service.ISysRoleMenuService;
import com.lms.admin.base.service.ISysRoleService;
import com.lms.admin.base.service.ISysUserRoleService;
import com.lms.common.entity.SysRole;
import com.lms.common.web.service.impl.WrapperServiceImpl;
import com.lms.common.web.utils.CheckEntityResult;
import com.lms.resource.service.utils.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends WrapperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final ISysUserRoleService sysUserRoleService;
    private final ISysRoleMenuService sysRoleMenuService;

    @Override
    public IPage<?> queryMapper(Page<SysRole> page, Map<String, Object> p) {
        return this.baseMapper.query(page, p);
    }

    @Override
    public CheckEntityResult beforeUpdate(SysRole entity, Serializable id) {
        entity.setUpdateBy(SecurityUtil.getUserName());
        entity.setUpdateTime(LocalDateTime.now());
        return CheckEntityResult.getInstance();
    }

    @Override
    public CheckEntityResult beforeInsert(SysRole entity) {
        CheckEntityResult result = CheckEntityResult.getInstance();
        // 判断新增角色是否存在重复code
        String roleCode = entity.getRoleCode();
        QueryWrapper<SysRole> params = new QueryWrapper<>();
        params.eq("role_code", roleCode);
        Long count = this.baseMapper.selectCount(params);
        if (count > 0) {
            result.add("role_code", "角色编码已存在，不允许重复创建！");
            return result;
        }
        entity.setCreateBy(SecurityUtil.getUserName());
        entity.setCreateTime(LocalDateTime.now());
        entity.setStatus(true);
        return result;
    }

    @Override
    public void toggleStatus(Long id) {
        SysRole role = this.getById(id);
        boolean status = role.getStatus();
        role.setStatus(!status);
        this.updateById(role);
    }

    @Override
    public SysRole getByCode(String code) {
        QueryWrapper<SysRole> params = new QueryWrapper<>();
        params.eq("role_code", code);
        return this.getOne(params);
    }

    @Override
    public boolean beforeDelete(Serializable id) {
        SysRole role = this.getById(id);
        // 超级管理员角色不允许被删除
        return !"ADMIN".equals(role.getRoleCode());
    }

    @Override
    public void afterDelete(Serializable id) {
        // 删除角色后，需要删除用户与角色的相关信息
        sysUserRoleService.removeByRoleId((Long) id);
        // 并且删除菜单与角色的相关信息
        sysRoleMenuService.removeByRoleId((Long) id);
    }
}
